// Copyright (c) 2024 NutPi. All rights reserved.
// Author: NutPi
// Website: https://nutpi.com
// WeChat: nutpi

import 'package:http/http.dart' as http;
import 'package:xml/xml.dart';
import '../models/article.dart';
import 'package:flutter/foundation.dart';

class RssService {
  String get rssUrl {
    if (defaultTargetPlatform == TargetPlatform.macOS) {
      return 'http://localhost:3000/api/rss';
    }
    return 'http://localhost:3000/api/rss';
  }

  Future<List<Article>> fetchArticles() async {
    debugPrint('开始获取RSS数据: $rssUrl');
    try {
      debugPrint('发起HTTP GET请求...');
      final response = await http.get(Uri.parse(rssUrl));

      debugPrint('收到响应 - 状态码: ${response.statusCode}');
      if (response.statusCode == 200) {
        debugPrint('开始解析XML数据...');
        final document = XmlDocument.parse(response.body);
        final items = document.findAllElements('item');
        debugPrint('找到 ${items.length} 条文章数据');

        final articles = items.map((item) => Article.fromXml(item)).toList();
        debugPrint('数据解析完成，成功获取 ${articles.length} 篇文章');
        return articles;
      } else {
        final error = '服务器响应错误: ${response.statusCode}';
        debugPrint('错误: $error');
        throw Exception(error);
      }
    } catch (e) {
      String errorMessage = '网络请求失败';
      if (e.toString().contains('Connection refused')) {
        errorMessage = '无法连接到代理服务器，请确保代理服务器已启动';
      } else if (e.toString().contains('XMLDocument.parse')) {
        errorMessage = 'RSS数据格式错误';
      }
      debugPrint('异常: $errorMessage - $e');
      throw Exception(errorMessage);
    }
  }
}
